package com.rc.saas.tenant.controller.car;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.redis.RedisLoader;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.area.PlatformArea;
import com.rc.saas.tenant.model.area.PlatformCity;
import com.rc.saas.tenant.model.area.PlatformProvince;
import com.rc.saas.tenant.model.car.TenantCarNumber;
import com.rc.saas.tenant.model.enterprise.EnterpriseMember;
import com.rc.saas.tenant.model.enterprise.EnterpriseMemberApply;
import com.rc.saas.tenant.model.fault.RcElecPileFaultRecord;
import com.rc.saas.tenant.model.platform.PlatformCarBrand;
import com.rc.saas.tenant.model.tenant.TenantRole;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.car.CarNumberSearch;
import com.rc.saas.tenant.service.area.PlatformAreaService;
import com.rc.saas.tenant.service.car.TenantCarNumberService;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberApplyService;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberService;
import com.rc.saas.tenant.service.platform.PlatformCarBrandService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.car.ExportCarNumberVo;
import com.rc.saas.tenant.vo.car.TenantCarNumberVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wangzhengwei
 * @create 2021/5/7
 */
@Controller
@RequestMapping("/tenantCarNumber")
public class TenantCarNumberController extends TenantBaseController {
    private final Logger logger = LoggerFactory.getLogger(TenantCarNumberController.class);

    /*车牌号验证*/
    private final String carNumRegex = "^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DFAB]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DFAB]))" +
            "|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$";

    @Autowired
    private TenantCarNumberService tenantCarNumberService;

    @Autowired
    private PlatformCarBrandService platformCarBrandService;

    @Autowired
    private EnterpriseMemberService enterpriseMemberService;

    @Autowired
    private EnterpriseMemberApplyService enterpriseMemberApplyService;

    @Autowired
    private RedisLoader redisLoader;

    @Autowired
    private PlatformAreaService areaService;

    @Autowired
    private TenantRoleService tenantRoleService;


    /**
     * 跳转 车牌库
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/templates/car/tenantCarNumber";
    }

    /**
     * 跳转 车牌库新增页面
     */
    @RequestMapping(value = "/addTenantCarNumber", method = RequestMethod.GET)
    public String addTenantCarNumber(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        //List<EnterpriseMember> enterpriseMembers = enterpriseMemberService.selectEnterpriseMembers(user.getTenantCode());
        TenantRole tu =  tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
        List<EnterpriseMemberApply> enterpriseMembers = new ArrayList<>();
        if (StringUtils.equals("3",tu.getRoleType())){
            enterpriseMembers = enterpriseMemberApplyService.getEnterpriseMemberApplys(user.getEnterpriseId());
        }else{
            enterpriseMembers = enterpriseMemberApplyService.getEnterpriseMemberApplys(null);
        }
        model.addAttribute("enterpriseMembers",enterpriseMembers);
        List<PlatformCarBrand> platformCarBrands = platformCarBrandService.selectCarBrand();
        model.addAttribute("platformCarBrands",platformCarBrands);
        List<PlatformProvince> provinces = areaService.listAllProvince();
        model.addAttribute("provinces", provinces);
        return "/templates/car/addTenantCarNumber";
    }

    /**
     * 跳转 车牌库编辑页面
     */
    @RequestMapping(value = "/editTenantCarNumber/{numberId}", method = RequestMethod.GET)
    public String editTenantCarNumber(Model model, @PathVariable("numberId") Long numberId) {
        TenantUser user = ShiroUtils.getSessionUser();
        TenantRole tu =  tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
        List<EnterpriseMemberApply> enterpriseMembers = new ArrayList<>();
        if (StringUtils.equals("3",tu.getRoleType())){
            enterpriseMembers = enterpriseMemberApplyService.getEnterpriseMemberApplys(user.getEnterpriseId());
        }else{
            enterpriseMembers = enterpriseMemberApplyService.getEnterpriseMemberApplys(null);
        }
        TenantCarNumberVo tenantCarNumber = tenantCarNumberService.selectById(numberId);
        model.addAttribute("tenantCarNumber", tenantCarNumber);
        //List<EnterpriseMember> enterpriseMembers = enterpriseMemberService.selectEnterpriseMembers(user.getTenantCode());

        model.addAttribute("enterpriseMembers",enterpriseMembers);
        List<PlatformCarBrand> platformCarBrands = platformCarBrandService.selectCarBrand();
        model.addAttribute("platformCarBrands",platformCarBrands);
        List<PlatformProvince> provinces = areaService.listAllProvince();
        model.addAttribute("provinces", provinces);
        return "/templates/car/editTenantCarNumber";
    }

    /**
     * 删除车辆
     */
   /* @RequestMapping(value = "/deleteTenantCarNumber/{numberId}", method = RequestMethod.GET)
    public TResponse deleteTenantCarNumber(Model model, @PathVariable("numberId") Long numberId) {*/
    @RequestMapping(value = "/deleteTenantCarNumber", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteTenantCarNumber(Long numberId) {
        try {
            tenantCarNumberService.deleteByPrimaryKey(numberId);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("删除失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 车牌库分页数据
     */
    @ResponseBody
    @RequestMapping(value = "/listPageCarNum", method = RequestMethod.GET)
    public WebPageInfo listPageCarNum(CarNumberSearch search) {
        TenantUser user = ShiroUtils.getSessionUser();
        TenantRole tu =  tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
        if (StringUtils.equals("3",tu.getRoleType())){
            search.setBaseEnterpriseId(user.getEnterpriseId());
        }
        PageInfo<TenantCarNumberVo> pageInfo = tenantCarNumberService.listPageByTenant(search);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 保存车牌库
     */
    @ResponseBody
    @RequestMapping(value = "/saveOrUpdateCarNum", method = RequestMethod.POST)
    public TResponse saveOrUpdateCarNum(TenantCarNumber tenantCarNumber) {
        TenantUser user = ShiroUtils.getSessionUser();
        //TResponse response = checkCarNumParam(tenantCarNumber);

        //完整车牌号
        String fullCarNum = tenantCarNumber.getCarNum();
        if (fullCarNum != null && fullCarNum.length() > 2) {
            String carArea = fullCarNum.substring(0, 1);
            String carLetter = fullCarNum.substring(1, 2);
            String carNum = fullCarNum.substring(2);
            tenantCarNumber.setCarArea(carArea);
            tenantCarNumber.setCarLetter(carLetter);
            tenantCarNumber.setCarNum(carNum);
        }
        Date date = new Date();
        tenantCarNumber.setLastUpdatedBy(user.getLoginName());
        tenantCarNumber.setLastUpdatedTime(date);
        if (tenantCarNumber.getNumberId() != null) {
            tenantCarNumberService.updateByPrimaryKeySelective(tenantCarNumber);
        } else {
            tenantCarNumber.setIsEnterprise("1");//企业会员
            tenantCarNumber.setTenantCode(user.getTenantCode());
            tenantCarNumber.setCreatedBy(user.getLoginName());
            tenantCarNumber.setCreatedTime(date);

            tenantCarNumberService.insertSelective(tenantCarNumber);
        }
        return TResponse.SUCCESS();

    }
    /**
     * 车牌库分页数据
     */
    /*@ResponseBody
    @RequestMapping(value = "/listPageCarNum", method = RequestMethod.GET)
    public WebPageInfo listPageCarNum(CarNumberSearch search) {
        TenantUser user = ShiroUtils.getSessionUser();
        search.setTenantCode(user.getTenantCode());
        PageInfo<TenantCarNumberVo> pageInfo = tenantCarNumberService.listPageByTenant(search);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }*/

    /**
     * 导出车辆列表信息
     * @param search
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/exportCarNumber", method = RequestMethod.GET)
    public TResponse exportCarNumber(CarNumberSearch search, HttpServletResponse response){
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        //导出拼接开始条数
        try {
            ExportUtils.setDefaultPaging(search);
            PageInfo<TenantCarNumberVo> pageInfo = tenantCarNumberService.listPageByTenant(search);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("车辆列表列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), TenantCarNumberVo.class).sheet("车辆列表列表").doWrite(pageInfo.getList());
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

    /**
     * 校验车牌库参数
     */
    private TResponse checkCarNumParam(TenantCarNumber tenantCarNumber) {
        if (tenantCarNumber == null) {
            return TResponse.FAIL("数据为null");
        }
        if (tenantCarNumber.getMemberId() == null) {
            return TResponse.FAIL("用户不能为空");
        }
        if (StringUtils.isBlank(tenantCarNumber.getCarNum()) || !tenantCarNumber.getCarNum().matches(carNumRegex)) {
            return TResponse.FAIL("车牌格式不符合");
        }
        return TResponse.SUCCESS();
    }


    /**
     * 根据城市id获取区域
     *
     * @param cityId
     * @return
     */
    @RequestMapping(value = "/getArea", method = RequestMethod.GET)
    @ResponseBody
    public TResponse getArea(String cityId) {
        List<PlatformArea> areas = areaService.listAreaByCityId(cityId);
        TResponse tResponse = TResponse.SUCCESS();
        tResponse.put(areas);
        return tResponse;
    }

    /**
     * 根据省id获取市
     *
     * @param provinceId
     * @return
     */
    @RequestMapping(value = "/getCity", method = RequestMethod.GET)
    @ResponseBody
    public TResponse getCity(String provinceId) {
        List<PlatformCity> cities = areaService.listCityByProvinceId(provinceId);
        TResponse tResponse = TResponse.SUCCESS();
        tResponse.put(cities);
        return tResponse;
    }
}
